package com.inspur.xiaoju.util;

import com.inspur.xiaoju.dto.FilterItem;

import java.util.ArrayList;  // 添加这个导入
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SurveyUtil {
    
    public static Map<String, Object> getFilter(List<FilterItem> filterList) {
        String[] allowFilterField = {"title", "remark", "surveyType", "curStatus.status", "subStatus.status"};
        Map<String, Object> result = new HashMap<>();
        
        for (FilterItem filterItem : filterList) {
            Map<String, Object> condition = new HashMap<>();
            
            for (FilterItem.Condition cond : filterItem.getCondition()) {
                boolean isAllowed = false;
                for (String field : allowFilterField) {
                    if (field.equals(cond.getField())) {
                        isAllowed = true;
                        break;
                    }
                }
                
                if (!isAllowed) {
                    continue;
                }
                
                switch (cond.getComparator()) {
                    case "$ne":
                        Map<String, Object> neCondition = new HashMap<>();
                        neCondition.put("$ne", cond.getValue());
                        condition.put(cond.getField(), neCondition);
                        break;
                    case "$regex":
                        Map<String, Object> regexCondition = new HashMap<>();
                        regexCondition.put("$regex", cond.getValue());
                        condition.put(cond.getField(), regexCondition);
                        break;
                    default:
                        condition.put(cond.getField(), cond.getValue());
                        break;
                }
            }
            
            switch (filterItem.getComparator()) {
                case "$or":
                    if (!result.containsKey("$or")) {
                        result.put("$or", new ArrayList<Map<String, Object>>());
                    }
                    ((List<Map<String, Object>>) result.get("$or")).add(condition);
                    break;
                default:
                    result.putAll(condition);
                    break;
            }
        }
        
        return result;
    }
}